<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>捕获异常</title>
	</head>

	<body>
		<script>
			const url = 'https://api.apiopen.top/api/sentences';

			const $ajax = (baseUrl) => {
				return new Promise((resolve, reject) => {
					window
						.fetch(baseUrl || url)
						.then((res) => res.json())
						.then((res) => {
							const { code } = res;
							if (code === 200) {
								resolve(res);
							} else {
								reject(res);
							}
						});
				});
			};

			/**
			 * 使用 try catch 可以捕获代码执行过程中的错误
			 * 让代码继续往下执行，但是不会中断执行
			 */
			async function send() {
				try {
					const result = await $ajax();
					console.log('请求成功', result);
				} catch (err) {
					const result = await $ajax(
						'https://api.apiopen.top/api/sentences'
					);
					console.log('错误重新发送', result);
				}
			}

			send();
		</script>
	</body>
</html>
